<script setup lang="ts">
  import { ref } from 'vue'
  import { addPatient, patientDetailApi, updatePatientApi } from '@/api/patient'
  import { onLoad } from '@dcloudio/uni-app'
  import type { PatientItem } from '@/types/patient'
  defineOptions({
    options: {
      styleIsolation: 'shared',
    },
  })

   interface Props {
    id: string
  }
  const props = defineProps<Props>()
  // 1. 表单数据
  const formData = ref({
    name: '',
    idCard: '',
    gender: 1,
    defaultFlag: 1,
  })
  //

  const formRef = ref<UniHelper.UniFormsInstance>()

  const fromRules: UniHelper.UniFormsRules = {
    name: {
      rules: [
        { required: true, errorMessage: '请填写患者姓名' },
        { pattern: /^[\u4e00-\u9fa5]{2,5}$/, errorMessage: '患者姓名位2-5位中文' },
      ],
    },
    idCard: {
      rules: [
        { required: true, errorMessage: '请填写患者身份证' },
        {
          pattern: /^\d{6}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/,
          errorMessage: '身份证号码有问题',
        },
      ],
    },
    gender: {
      rules: [
        {
          validateFunction: (rule, value, data, callback) => {
            const sexNum = Number(formData.value.idCard.charAt(16))
            // 奇数为男  偶数位女
            const isGenderMatch = sexNum % 2 === value % 2
            return isGenderMatch || callback('性别与身份证号码不匹配')
          },
        },
      ],
    },
  }

  const isLoading = ref(false)

  const onSubmit = async () => {
    try {
      await formRef.value?.validate!()
      isLoading.value = true
     if (props.id) {
        // 编辑
        await updatePatientApi({ id: props.id, ...formData.value } as PatientItem)
      } else {
        await addPatient(formData.value)
        // 返回上一页
      }
      uni.showToast({ title: props.id ? '更新成功' : '添加成功' })
      uni.navigateBack()
    } catch (error) {
      console.log('error  ----->  ', error)
    } finally {
      isLoading.value = false
    }
}
 onLoad(async () => {
    if (!props?.id) return
    uni.setNavigationBarTitle({ title: '编辑患者' })
    const res = await patientDetailApi(props?.id)
    formData.value = {
      name: res.name,
      idCard: res.idCard,
      gender: res.gender!,
      defaultFlag: res.defaultFlag,
    }
  })
</script>

<template>
  <scroll-page>
    <view class="archive-page">
      <uni-forms border label-width="220rpx" ref="formRef" :model="formData" :rules="fromRules">
        <uni-forms-item label="患者姓名" name="name">
          <uni-easyinput
            placeholder-style="color: #C3C3C5; font-size: 32rpx"
            :style="{ color: '#121826' }"
            :input-border="false"
            :clearable="false"
            placeholder="请填写真实姓名"
            v-model="formData.name"
          />
        </uni-forms-item>
        <uni-forms-item label="患者身份证号" name="idCard">
          <uni-easyinput
            placeholder-style="color: #C3C3C5; font-size: 32rpx"
            :style="{ color: '#121826' }"
            :input-border="false"
            :clearable="false"
            placeholder="请填写身份证号"
            v-model="formData.idCard"
          />
        </uni-forms-item>
        <uni-forms-item label="患者性别" name="gender">
          <uni-data-checkbox
            v-model="formData.gender"
            mode="tag"
            selectedColor="#16C2A3"
            :localdata="[
              { text: '男', value: 1 },
              { text: '女', value: 0 },
            ]"
          />
        </uni-forms-item>
        <uni-forms-item label="默认就诊人">
          <view class="uni-switch">
            <!-- !! !!等价于 Boolean 强制类型转为Boolean -->
            <switch
              :checked="!!formData.defaultFlag"
              @change="formData.defaultFlag = $event.detail.value ? 1 : 0"
              color="#20c6b2"
              style="transform: scale(0.7)"
            />
          </view>
        </uni-forms-item>
        <button class="uni-button" :loading="isLoading" @click="onSubmit">保存</button>
      </uni-forms>
    </view>
  </scroll-page>
</template>

<style lang="scss">
  @import './form.scss';
</style>
